/**
 * Created by yang on 15/1/8.
 */

var http = require('http');
var path = require('path');
var config = require('../config');
var express = require('express');
var core = require('./index');

module.exports = Server = function(name,port){
    this.name = name;//app name
    this.port = port;//app port
    this.routers = {};
    this.app = express();
}

Server.prototype.exitProcess = function(){
    process.exit(1);
}

Server.prototype.loadRouters = function(){
    console.log(this.name + ' loadRouters doing nothing!');
}

Server.prototype._loadRouters = function(callback){
    this.loadRouters();
    if(callback) callback();
}



Server.prototype.runServer = function(){
    var scope = this;
    var port =  this.port;
    var log = process.core.log;
    http.createServer(this.app).listen(port,function(){
        log.info(scope.name + ' is listening on port ' + port);
    });
}


Server.prototype.useCookieParser = function(){
    /*
     * 启用cookie解析
     * */
    var cookieParser = require('cookie-parser');
    this.app.use(cookieParser(config.sessionKey));
}

Server.prototype.useBodyParser = function(){
    /*
     * 启动body解析
     * */
    var bodyParser = require('body-parser');
    var methodOverride = require('method-override');
    this.app.use(bodyParser.urlencoded({ extended: false }));
    this.app.use(bodyParser.json());
    this.app.use(methodOverride());
}

Server.prototype.useMulterUpload = function(){
    /*
     * 上传设置
     * */
    var multer  = require('multer');
    var uploadPath = path.join(core.getProjectRoot(),'uploads');
    this.app.use(multer({
        dest:uploadPath,
        limits:{
            fileSize:2*1024*1024 //上传文件大小限制在2mb
        },
        rename: function (fieldname, filename) {
            return filename.replace(/\W+/g, '-').toLowerCase() + Date.now()
        }
    }));
    this.app.use('/uploads', express.static(uploadPath));
}

Server.prototype.useSession = function(){
    /*
     * 启用session机制
     * */
    var session = require('express-session');
    this.app.use(session({
        secret: config.sessionKey,
        saveUninitialized: true,
        cookie: {httpOnly: false},
        resave: true}));

}

Server.prototype.useMogSession = function(){
    /*
     * 将session存入mongodb防止应用意外重启
     * */
    var session = require('express-session');
    var MongoStore = require('connect-mongo')(session);
    var sessionStore =  new MongoStore({
        url:config.dbConfig.dbAddress,
        autoReconnect: true, // Default
        w: 1, // Default,
        ssl: false // Default
    });

    this.app.use(session({
        secret: config.sessionKey,
        saveUninitialized: true,
        resave: true,
        store:sessionStore
    }));
}

Server.prototype.useCrossSetting = function(){
    /*
     *启用跨域限制
     **/
    this.app.use(function(req, res, next) {
        res.header("Access-Control-Allow-Origin", "*");
        res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
        res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
        res.header("X-Powered-By",'3.2.1')
        if(req.method=="OPTIONS"){
            res.send(200);//让options请求快速返回
        }else{
            next();
        }
    });
}

Server.prototype.useCoreLogger = function(){
    process.core.log.add(this);
}

Server.prototype.loadFrontend = function(){
    //挂载前端路径
    this.app.use(express.static(path.join(core.getProjectRoot(), 'frontend')));
}

Server.prototype.loadMobileFrontend = function(){
    //挂载前端路径
    this.app.use(express.static(path.join(core.getProjectRoot(), 'frontend/mobile')));
}

Server.prototype.loadAdminFrontend = function(){
    //挂载前端路径
    this.app.use(express.static(path.join(core.getProjectRoot(), 'frontend/admin')));
}

Server.prototype.useXmlParse = function(){
    //启用xml解析
    var xmlParse = require('./utils/xmlParser');
    this.app.use(xmlParse);
}

Server.prototype.init = function(){
    console.log(this.name + ' init doing nothing!');
}

Server.prototype._init = function (callback) {
    this.init();
    this._loadRouters(callback);
}

Server.prototype.run = function(){
    var scope = this;
    core.init(function(err){
        if(!err){
            scope._init(function(){
                scope.runServer();
            });
        }else{
            scope.exitProcess();
        }
    });
}










